/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.KwMasterTearcher;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.mapper.MasterTearcherMapper;
import me.zhengjie.pojo.entity.MasterTearcher;
import me.zhengjie.repository.KwMasterTearcherRepository;
import me.zhengjie.service.KwMasterTearcherService;
import me.zhengjie.service.dto.KwMasterTearcherDto;
import me.zhengjie.service.dto.KwMasterTearcherQueryCriteria;
import me.zhengjie.service.mapstruct.KwMasterTearcherMapper;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-06-28
 **/
@Service
@RequiredArgsConstructor
public class KwMasterTearcherServiceImpl implements KwMasterTearcherService {

    private final KwMasterTearcherRepository kwMasterTearcherRepository;
    private final KwMasterTearcherMapper kwMasterTearcherMapper;
    private final MasterTearcherMapper masterTearcherMapper;

    @Override
    public Map<String, Object> queryAll(KwMasterTearcherQueryCriteria criteria, Pageable pageable) {
        Page<KwMasterTearcher> page = kwMasterTearcherRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(kwMasterTearcherMapper::toDto));
    }

    @Override
    public List<KwMasterTearcherDto> queryAll(KwMasterTearcherQueryCriteria criteria) {
        return kwMasterTearcherMapper.toDto(kwMasterTearcherRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public KwMasterTearcherDto findById(Integer id) {
        KwMasterTearcher kwMasterTearcher = kwMasterTearcherRepository.findById(id).orElseGet(KwMasterTearcher::new);
        ValidationUtil.isNull(kwMasterTearcher.getId(), "KwMasterTearcher", "id", id);
        return kwMasterTearcherMapper.toDto(kwMasterTearcher);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Object> create(KwMasterTearcher resources) {
        if (Objects.equals(resources.getType(), "1")) {
            if (StringUtils.isBlank(resources.getJobNumber())) throw new ParameterException("类型为报名的教师工号为必填");
            QueryWrapper<MasterTearcher> jobNumberWrapper = new QueryWrapper<>();
            jobNumberWrapper.eq("job_number", resources.getJobNumber());
            Integer jobNumberCount = masterTearcherMapper.selectCount(jobNumberWrapper);
            if (jobNumberCount != 0) throw new ParameterException("工号已存在");
        }
        QueryWrapper<MasterTearcher> idCardWrapper = new QueryWrapper<>();
        idCardWrapper.eq("id_card", resources.getIdCard());
        Integer idCardCount = masterTearcherMapper.selectCount(idCardWrapper);
        if (idCardCount != 0) throw new ParameterException("身份证已存在");
        QueryWrapper<MasterTearcher> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq("phone", resources.getPhone());
        Integer phoneCount = masterTearcherMapper.selectCount(phoneWrapper);
        if (phoneCount != 0) throw new ParameterException("手机号已存在");
        return new ResponseEntity<>(kwMasterTearcherMapper.toDto(kwMasterTearcherRepository.save(resources)), HttpStatus.OK);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KwMasterTearcher resources) {
        QueryWrapper<MasterTearcher> jobNumberWrapper = new QueryWrapper<>();
        jobNumberWrapper.eq("job_number", resources.getJobNumber())
                .ne("id", resources.getId());
        Integer jobNumberCount = masterTearcherMapper.selectCount(jobNumberWrapper);
        if (jobNumberCount != 0) throw new ParameterException("工号已存在");
        QueryWrapper<MasterTearcher> idCardWrapper = new QueryWrapper<>();
        idCardWrapper.eq("id_card", resources.getIdCard())
                .ne("id", resources.getId());
        Integer idCardCount = masterTearcherMapper.selectCount(idCardWrapper);
        if (idCardCount != 0) throw new ParameterException("身份证已存在");
        QueryWrapper<MasterTearcher> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq("phone", resources.getPhone())
                .ne("id", resources.getId());
        Integer phoneCount = masterTearcherMapper.selectCount(phoneWrapper);
        if (phoneCount != 0) throw new ParameterException("手机号已存在");
        KwMasterTearcher kwMasterTearcher = kwMasterTearcherRepository.findById(resources.getId()).orElseGet(KwMasterTearcher::new);
        ValidationUtil.isNull(kwMasterTearcher.getId(), "KwMasterTearcher", "id", resources.getId());
        kwMasterTearcher.copy(resources);
        kwMasterTearcherRepository.save(kwMasterTearcher);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            kwMasterTearcherRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<KwMasterTearcherDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (KwMasterTearcherDto kwMasterTearcher : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("工号", kwMasterTearcher.getJobNumber());
            map.put("姓名", kwMasterTearcher.getNameCn());
            map.put("身份证", kwMasterTearcher.getIdCard());
            map.put("手机号", kwMasterTearcher.getPhone());
            map.put("部门id", kwMasterTearcher.getDeptId());
            map.put("监考教师类型（0：上报，1：报名）", kwMasterTearcher.getType());
            map.put("删除标识（0：未删除，1：已删除）", kwMasterTearcher.getDelFlag());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}